import React, { Component } from 'react';
import { Tag , Typography, Rate, Row, Col, Button, Comment, Tooltip, List, message, Image, ConfigProvider, Empty  } from 'antd';
import { ReadOutlined, DownloadOutlined, UnorderedListOutlined } from '@ant-design/icons';
import { Link } from 'react-router-dom';
import Wheaders from '../../components/Headers';
import Http from '../../util/http';
import { WindManUtils } from '../../util/utils';
import moment from 'moment';
import './index.less'

const { Paragraph } = Typography;
const COMMENT_PAGE_SIZE = 50;

class Details extends Component {
    constructor(props) {
        super(props);
        this.state = {
            novelId: props.location.state.novelId,
            novelInfo: {},
            lastChapter: {},
            lastRead: null,
            randomRecMap: [],
            commentList: [],
            page: 1,
            iscollected: false,
            initLoading: true,
            loading: false,
            action: null
        }
        this.detailsE = null;
    }

    render() {
        const { novelInfo, lastChapter, randomRecMap, lastRead, initLoading, iscollected, loading } = this.state;
        const loadMore =
            !initLoading && !loading ? (
                <div
                style={{
                    textAlign: 'center',
                    marginTop: 12,
                    height: 32,
                    lineHeight: '32px',
                }}
                >
                <Button onClick={this.onLoadMore}>查看更多</Button>
                </div>
            ) : null;

        return (
            <div ref={ node => this.detailsE = node} className={'details'}>
                <Wheaders left={'返回'} middle={'详情'} right={'我的'} />
                <div className={'con'}>
                    <div className={'bok'}>
                        <div className={'content'}>
                            <div className={'content-header'}>
                                <Image className={'ant-img'} src={novelInfo.coverUrl} preview={false}  fallback={'http://image.hanlingsha.love/lwa/novel/lwa-default-novel-cover.jpeg'} />
                            </div>
                            <div className={'content-body'}>
                                <h2 className={'title'}>
                                    {novelInfo.novelName}
                                </h2>
                                <div className='score '>
                                    <Rate className={'scoring'} disabled value={novelInfo.rate} count={5}
                                    allowHalf={true} />
                                    <div className={'ant-rate-text scoring-text'}>{WindManUtils.formatNum(novelInfo.touchNum)} 点击</div>
                                </div>
                                <p className={'classify'}>
                                    <Tag className={'tag'}>{novelInfo.tagName}</Tag>
                                    <Tag className={'tag'}>{novelInfo.authorName}</Tag>
                                </p>
                                <p className={'classify'}>
                                    <span className={'tag'}>{novelInfo.isDone === 'Y' ? '已完结' : '连载中'}</span>
                                    <span className={'tag author'}>{novelInfo.wordsNum}</span>
                                </p>
                            </div>
                        </div>
                        <div className={'btn'}>
                            <Row>
                                <Col className='btn-text' span={24}>
                                    <ReadOutlined style={{ color: iscollected ? 'rgba(0, 0, 0, 0.25)' : '#666666' }} className={'btn-icon'} />
                                    <Button type='text' onClick={this.handleCollection.bind(this, novelInfo.novelId)} disabled={(novelInfo && novelInfo.collected) || iscollected}>加入书架</Button>
                                </Col>
                                {/* <Col className="btn-text" span={12}>
                                    <DownloadOutlined className={"btn-icon"} />
                                    <Button type="text">下载本书</Button>
                                </Col> */}
                            </Row>
                        </div>
                    </div>
                    <ConfigProvider
                        renderEmpty={() => (
                            <Empty description={<span> 暂无简介~</span>} />
                        )}>
                        <Paragraph
                            className={'remark'}
                            ellipsis={{ rows: 2,
                                expandable: true,
                                symbol: '展开',
                                onEllipsis: function(ellipsis){

                                },
                                onExpand: function(event) {

                                }
                            }}>
                            {novelInfo.intro}
                        </Paragraph>
                    </ConfigProvider>
                    <div className={'news-content'}>
                        <Row className={'news'}>
                            <Col span={4}>
                                <Link  className={'catalog'}  to={{pathname:'/catalogue', state: { novelInfo: novelInfo }}}>
                                    <UnorderedListOutlined />
                                    <span>目录</span>
                                </Link>
                            </Col>
                            <Col span={20}>
                                <Link  className={'reading'}  to={{pathname:'/reading', state:{
                                    novelInfo: this.state.novelInfo,
                                    orderNum: lastRead ? lastRead.orderNum : 1,
                                }}}>
                                    <Row>
                                        <Col span={16}>
                                            {lastChapter ? <div className={'new'}>{WindManUtils.changeChapterStr(lastChapter.chapterName)}</div> : '无数据'}
                                        </Col>
                                        <Col span={8}>
                                            <div className={'time'}>{moment(novelInfo.updateTime *1000).format('MM-DD HH:mm')}</div>
                                        </Col>
                                    </Row>
                                </Link>
                            </Col>
                        </Row>
                    </div>
                    <div className={'comment'}>
                        <h2>
                            热门书评
                            <Button className={'whrite-btn'} onClick={this.createComment.bind(this)}>写评论</Button>
                        </h2>
                        <ConfigProvider
                            renderEmpty={() => (
                                <Empty description={<span> 暂无评论~</span>} />
                            )}>
                            <List
                                className='comment-list'
                                itemLayout='horizontal'
                                loadMore={
                                    // 当前页数据小于 50 条 证明是最后一页
                                    this.state.commentList.length < COMMENT_PAGE_SIZE ? null : loadMore
                                }
                                dataSource={this.state.commentList}
                                renderItem={item => (
                                    <List.Item>
                                        <Comment
                                        author={item.userName}
                                        avatar={item.headpic}
                                        content={item.content}
                                        datetime={<Tooltip title={moment( +item.addTime *1000).format('YYYY-MM-DD HH:mm:ss')}>
                                            <span>{moment(+item.addTime *1000).format('YYYY-MM-DD HH:mm:ss')}</span>
                                        </Tooltip>}
                                        />
                                    </List.Item>
                                )}
                            />
                        </ConfigProvider>
                    </div>
                    <div className={'author-otherBooks'}>
                        <h2>热门同类作品</h2>
                        <div className={'youlike'}>
                            <Row>
                                {
                                randomRecMap.map( (item, index) => {
                                    return (
                                        <Col className={'item'} key={index} span={6}>
                                            <div onClick={ () => {
                                                this.setState({novelId: item.novelId});
                                            }}>
                                                <span className={'like-book'}>
                                                    <Image className={'ant-img'} src={item.coverUrl} preview={false}  fallback={'http://image.hanlingsha.love/lwa/novel/lwa-default-novel-cover.jpeg'} />
                                                </span>
                                                <p className='like-title'>
                                                    {item.novelName}
                                                </p>
                                            </div>
                                        </Col>);
                                })
                                }
                            </Row>
                            <Button onClick={this.getRandomRec.bind(this)} style={{ padding: '10px 0'}} type={'text'} block>换一换</Button>
                        </div>
                    </div>

                    <div className={'wap-read'}>
                        <Button className={'btn'} type='primary' block onClick={this.goReading.bind(this, lastRead)}>
                            { lastRead ? '免费阅读' : '继续阅读'}
                        </Button>
                    </div>
                </div>
            </div>
        );
    }

    shouldComponentUpdate(nextProps, nextState) {
        if (nextState.novelId !== this.state.novelId){
            this.setState({
                novelId: nextState.novelId,
                novelInfo: {},
                lastChapter: {},
                lastRead: null,
                randomRecMap: [],
                commentList: [],
                page: 1,
                initLoading: true,
                loading: false,
                action: null
            })
            // 获取小说详情信息
            this.getNovelDetail(nextState.novelId);
            // 获取详情页推荐
            this.getRandomRec();
            // 获取评论
            this.getCommentList(nextState.novelId, this.state.page);
            this.detailsE.scrollIntoView();
        }
        return true;
    }

    UNSAFE_componentWillMount() {

    }

    componentDidMount (){
        const { novelId } = this.state;
        // 获取小说详情信息
        this.getNovelDetail(novelId);
        // 获取详情页推荐
        this.getRandomRec();
        // 获取评论
        this.getCommentList(novelId, this.state.page);
    }

    handleCollection(novelId) {
        Http.get('/Shelf/add', {
            novelId
        }).then( res => {
            message.success('加入书架成功', 1, () => {
                this.setState({iscollected: true});
            });
        })
    }

    getNovelDetail(novelId) {
        Http.get('/Novel/getNovelDetail', {
            novelId,
        }).then( res => {
            this.setState({
                novelInfo: res.resultData.novelInfo,
                lastChapter: res.resultData.lastChapter,
                lastRead: res.resultData.lastRead,
                iscollected: res.resultData.novelInfo.collected,
            });
        });
    }

    getRandomRec() {
        Http.get('/Novel/getRandomRec').then( res => {
            this.setState({ randomRecMap: res.resultData});
        });
    }

    goReading(lastRead) {
        this.props.history.push({pathname: '/reading' , state:{
            novelInfo: this.state.novelInfo,
            orderNum: lastRead ? lastRead.orderNum : 1,
        }});
    }

    createComment() {
        this.props.history.push({pathname: '/createcomment', state: {
            novelId: this.state.novelInfo.novelId
        }});
    }

    getCommentList(id, page = 1) {
        Http.get('/Comment/getCommentList', {
            novelId: id,
            page,
        }).then( res => {
            if (res.resultData.length === 0) {
                return this.setState({initLoading: true});
            }
            const commentList = [...this.state.commentList, ...res.resultData]
            this.setState({ commentList, initLoading: false, page});
        });
    }

    onLoadMore = () => {
        this.getCommentList(this.state.novelInfo.novelId, +this.state.page + 1);
    };
}
export default Details;